//
//  NDContactsView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/30.
//

import SwiftUI

struct NDContactsView: View, TitledView {
    var navigationTitle: String {
        return title ?? "My Contacts"
    }
    
    let title: String?
    let productId: Int
    let orderNum: String
    @State private var showEnumViewPopup = false
    @State private var showContactPicker = false
    @State var phoneNumber: String?
    @State var fullName: String?
    @State var showPermissAlert = false
    
    @StateObject var viewModel: NDContactsViewModel

    init(title: String?, productId: Int, orderNum: String) {
        self.title = title
        self.productId = productId
        self.orderNum = orderNum
        self._viewModel = StateObject(wrappedValue: NDContactsViewModel(productId: productId, orderNum: orderNum))
    }

    var body: some View {
        
        let permissButtons: [NDPopupButton] = [
            NDPopupButton.init(localizedString("Open setting")) {
                showPermissAlert = false
                UIApplication.shared.openAppSettings()
            },
            NDPopupButton.init(localizedString("Cancel"), style: .underline) {
                showPermissAlert = false
            }
        ]
        
        let navigationConfig = NavigationConfig(
            title: navigationTitle,
            showSystemBackButton: false
        )
        NDAuthenBaseView(navigationConfig: navigationConfig) {
            
            VStack(spacing: 0) {
                // 顶部图片
                Image(WJAppEnvironment.shared.currentCountry == .india ? "contacts_top_icon" : "contacts_top_icon_id")
                    .scaledToFit()
                    .frame(height: 150)
                    .padding(.bottom, 20)
                
                if let pachist = viewModel.contactsModel?.egrirecognizeic?.pachist {
                    LazyVStack(spacing: 20) {
                        ForEach(Array(pachist.enumerated()), id: \.offset) { index, pachist in
                            VStack {
                                NDContactsSection(viewModel: viewModel,
                                                  pachist: pachist,
                                                  commonActionSectionIndex: index) {
                                    
                                    self.showEnumViewPopup = true
                                    
                                } onClickContactsButton: {
                                    
                                    NDContactTool.shared.requestAccess { granted in
                                        if granted {
                                            showContactPicker = true
                                        } else {
                                            showPermissAlert = true
                                        }
                                    }
                                }
                            }
                        }
                    }
                    .frame(maxWidth: .infinity)
                    .background(Color(hex: "#FFFFFF"))
                    .cornerRadius(20)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color(hex: "#271F24"), lineWidth: 1)
                    )
                    .padding(.horizontal, 16)
                    .padding(.top, -45)
                }
                
                Spacer()
                
                nextStepButton
                    .padding(.top, 10)
                    .padding(.bottom, 20)
                    .background(Color.white.ignoresSafeArea(.all, edges: .bottom))
            }
        }
        .onAppear {
            if viewModel.contactsModel == nil {
                viewModel.loadContactsData()
            }
            viewModel.startTimeStamp = Int(Date().timeIntervalSince1970)
        }
        .onChange(of: viewModel.isLoading) { isLoading in
            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    if viewModel.errorMessage == nil {
                        
                        NDProgressHUD.dismiss()
                    }
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .onChange(of: phoneNumber ?? "") { contact in
            viewModel.updateEnergyifyField(at: viewModel.commonActionSectionIndex,
                                           field: .pressoutside,
                                           value: contact)
        }
        .onChange(of: fullName ?? "") { contact in
            viewModel.updateEnergyifyField(at: viewModel.commonActionSectionIndex,
                                           field: .interestacle,
                                           value: contact)
        }
        .sheet(isPresented: $showContactPicker) {
            NDContactsPicker(phoneNumber: $phoneNumber,
                             fullName: $fullName)
                .ignoresSafeArea(.all, edges: .all)
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                        if viewModel.isUploadEvent == false {
                            NDEventAnallyticsTool.uploadContactsEvent {
                                viewModel.isUploadEvent = true
                            }
                        }
                    }
                }
        }
        .onChange(of: viewModel.saveSuccess) { success in
            if success {
                NotificationCenter.default.post(name: .followUpCurrentProductNotification,
                                                object: nil,
                                                userInfo: nil)

            }
        }
        .ndAlertOnWindow(isPresented: $showPermissAlert,
                         title: "",
                         tips: nil,
                         message: localizedString("NSContactsUsageDescription"),
                         backgroundImage: "common_alert_bg",
                         buttons: permissButtons)
        .ndCustomPopupOnWindow(isPresented: $showEnumViewPopup,
                               style: .actionSheet) {
            NDPersonalEnumView(
                title: viewModel.title,
                dataSource: viewModel.courseatics,
                onSelectionChanged: { index, item in
                    print("选中了第 \(index) 项: \(item?.interestacle ?? "未知")")
                },
                onConfirmAction: { item in
                    print("确认选择: \(item?.interestacle ?? "未知")")
                    showEnumViewPopup = false
                    if let olig = item?.olig {
                        viewModel.updateEnergyifyField(at: viewModel.commonActionSectionIndex,
                                                       field: .olig,
                                                       value: String(olig))
                    }
                }, onCloseAction: {
                    showEnumViewPopup = false
                }
            )
            .padding(.horizontal, 5)
            .background(Color(hex: "#FFFFFF"))
        }
    }
    
    var nextStepButton: some View {
        Button(action: nextStepAction) {
            Text(localizedString("Next step"))
                .frame(maxWidth: .infinity)
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .padding(.horizontal, 15)
                .padding(.vertical, 10)
                .frame(height: 48)
                .background(Color(hex: "#271F24"))
                .clipShape(Capsule())
                .contentShape(Rectangle())
        }
        .padding(.horizontal, 16)
    }
    
    func nextStepAction() {
        viewModel.saveContactsData()
    }
}
